package com.scs.application.modules.msg.sender;

import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.modules.msg.entity.InnerInbox;
import com.scs.application.modules.msg.entity.InnerNotice;
import com.scs.application.modules.msg.model.InnerNoticeMessage;
import com.scs.application.modules.msg.service.InnerInboxService;
import com.scs.application.modules.msg.service.InnerNoticeService;
import com.scs.application.modules.sys.service.UserService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 */
@Slf4j
@Component
public class InnerNoticeMessageSender extends MessageSender<InnerNoticeMessage> {

    @Autowired
    private InnerNoticeService innerNoticeService;


    @Autowired
    private InnerInboxService innerInboxService;

    @Autowired
    private UserService userService;


    @Override
    protected void beforeSend(InnerNoticeMessage msg) {
        super.beforeSend(msg);
//        if (msg.getPriority() == null) {
//            throw new BusinessException("站内信发送失败：优先级不能为空");
//        }

        if (msg.getContentType() == null) {
            throw new BusinessException("站内信发送失败：内容类型不能为空");
        }
    }

    @Override
    protected void doSend(InnerNoticeMessage msg) {
        String receiverCodes = msg.getReceiverCodes();


        InnerNotice innerNotice = new InnerNotice();
        innerNotice.setTitle(msg.getTitle())
                .setContent(msg.getContent())
//                .setPriority(msg.getPriority().getCode())
//                .setContentType(msg.getContentType().getCode())
                .setPriority(msg.getPriority())
                .setContentType(msg.getContentType())
                .setReceiverCodes(receiverCodes)
                .setReceiverGroup(msg.getReceiverGroup())
                .setReceiverType(msg.getReceiverType())
                .setReceiverNames(msg.getReceiverNames())
                .setGmtSend(new Date())
                .setSender(msg.getSender());

        innerNoticeService.save(innerNotice);

        String[] receiverCodeArr = receiverCodes.split(",");
        List<InnerInbox> innerInboxes = Lists.newArrayListWithCapacity(receiverCodeArr.length);
        for (String code : receiverCodeArr) {
            InnerInbox inbox = new InnerInbox();
            inbox.setInnerNoticeId(innerNotice.getId())
                    .setReceiverUserCode(code)
                    .setReceiverUserName(code)
                    .setIsRead(GlobalConsts.NO)
                    .setGmtRead(null);
            innerInboxes.add(inbox);
        }
        if(!innerInboxes.isEmpty()){
            innerInboxService.saveBatch(innerInboxes);
        }

        log.debug("站内信发送成功，接收人：{}", receiverCodes);
    }
}
